package com.example.chamberlainserver.Service.impl;

import com.example.chamberlainserver.Entry.CounselorClass;
import com.example.chamberlainserver.Service.CounselorClassService;
import com.example.chamberlainserver.dto.CounselorClassDTO;
import com.example.chamberlainserver.dto.PageResult;
import com.example.chamberlainserver.mapper.CounselorClassMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 辅导员班级关联服务实现类
 */
@Service
@Transactional
public class CounselorClassServiceImpl implements CounselorClassService {

    @Autowired
    private CounselorClassMapper counselorClassMapper;

    @Override
    public List<CounselorClass> getAllCounselorClasses() {
        return counselorClassMapper.selectAll();
    }

    @Override
    public CounselorClass getCounselorClassById(Long id) {
        return counselorClassMapper.selectById(id.intValue());
    }

    @Override
    public List<CounselorClass> getCounselorClassesByCounselorId(Long counselorId) {
        return counselorClassMapper.selectByCounselorId(counselorId.intValue());
    }

    @Override
    public List<CounselorClass> getCounselorClassesByClassId(Long classId) {
        return counselorClassMapper.selectByClassId(classId.intValue());
    }

    @Override
    public CounselorClass getCounselorClassByCounselorAndClass(Long counselorId, Long classId) {
        return counselorClassMapper.selectByCounselorAndClass(counselorId.intValue(), classId.intValue());
    }

    @Override
    public PageResult<CounselorClass> getCounselorClassesByPageWithDetails(int page, int size, String counselorName, String className, String department) {
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 查询数据
        List<CounselorClass> counselorClasses = counselorClassMapper.selectByPageWithDetails(offset, size, counselorName, className, department);
        
        // 查询总数
        Integer total = counselorClassMapper.countAll(counselorName, className, department);
        
        return new PageResult<>(page, size, (long) total, counselorClasses);
    }

    @Override
    public boolean clearPrimaryCounselor(Long classId) {
        return counselorClassMapper.clearPrimaryCounselor(classId.intValue()) > 0;
    }

    @Override
    public int assignCounselorToClasses(Long counselorId, List<Long> classIds, boolean isPrimary) {
        int count = 0;
        for (Long classId : classIds) {
            CounselorClassDTO dto = new CounselorClassDTO();
            dto.setCounselorId(counselorId);
            dto.setClassId(classId);
            dto.setIsPrimary(isPrimary);
            
            try {
                createCounselorClass(dto);
                count++;
            } catch (Exception e) {
                // 忽略已存在的关联关系
            }
        }
        return count;
    }

    @Override
    public int assignClassToCounselors(Long classId, List<Long> counselorIds, Long primaryCounselorId) {
        int count = 0;
        for (Long counselorId : counselorIds) {
            CounselorClassDTO dto = new CounselorClassDTO();
            dto.setCounselorId(counselorId);
            dto.setClassId(classId);
            dto.setIsPrimary(counselorId.equals(primaryCounselorId));
            
            try {
                createCounselorClass(dto);
                count++;
            } catch (Exception e) {
                // 忽略已存在的关联关系
            }
        }
        return count;
    }

    @Override
    public boolean existsCounselorClass(Long counselorId, Long classId) {
        return counselorClassMapper.selectByCounselorAndClass(counselorId.intValue(), classId.intValue()) != null;
    }

    @Override
    public CounselorClass getPrimaryCounselorByClassId(Long classId) {
        List<CounselorClass> counselorClasses = counselorClassMapper.selectByClassId(classId.intValue());
        return counselorClasses.stream()
                .filter(cc -> cc.getIsPrimary() != null && cc.getIsPrimary())
                .findFirst()
                .orElse(null);
    }

    @Override
    public CounselorClass createCounselorClass(CounselorClassDTO counselorClassDTO) {
        // 检查关联关系是否已存在
        if (counselorClassMapper.selectByCounselorAndClass(counselorClassDTO.getCounselorId().intValue(), counselorClassDTO.getClassId().intValue()) != null) {
            throw new RuntimeException("该辅导员已关联此班级");
        }
        
        CounselorClass counselorClass = new CounselorClass();
        BeanUtils.copyProperties(counselorClassDTO, counselorClass);
        counselorClass.setCreateTime(LocalDateTime.now());
        counselorClass.setUpdateTime(LocalDateTime.now());
        
        // 设置默认值
        if (counselorClass.getIsPrimary() == null) {
            counselorClass.setIsPrimary(false);
        }
        if (counselorClass.getAssignTime() == null) {
            counselorClass.setAssignTime(LocalDateTime.now());
        }
        
        counselorClassMapper.insert(counselorClass);
        return counselorClass;
    }

    @Override
    public int createCounselorClasses(List<CounselorClassDTO> counselorClassDTOs) {
        if (counselorClassDTOs == null || counselorClassDTOs.isEmpty()) {
            return 0;
        }
        
        List<CounselorClass> counselorClasses = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        
        for (CounselorClassDTO dto : counselorClassDTOs) {
            // 检查关联关系是否已存在
            if (counselorClassMapper.selectByCounselorAndClass(dto.getCounselorId().intValue(), dto.getClassId().intValue()) != null) {
                continue; // 跳过已存在的关联关系
            }
            
            CounselorClass counselorClass = new CounselorClass();
            BeanUtils.copyProperties(dto, counselorClass);
            counselorClass.setCreateTime(now);
            counselorClass.setUpdateTime(now);
            
            // 设置默认值
            if (counselorClass.getIsPrimary() == null) {
                counselorClass.setIsPrimary(false);
            }
            if (counselorClass.getAssignTime() == null) {
                counselorClass.setAssignTime(now);
            }
            
            counselorClasses.add(counselorClass);
        }
        
        if (counselorClasses.isEmpty()) {
            return 0;
        }
        
        return counselorClassMapper.batchInsert(counselorClasses);
    }

    @Override
    public CounselorClass updateCounselorClass(Long id, CounselorClassDTO counselorClassDTO) {
        CounselorClass existingCounselorClass = counselorClassMapper.selectById(id.intValue());
        if (existingCounselorClass == null) {
            throw new RuntimeException("关联关系不存在");
        }
        
        // 如果更新了辅导员或班级，检查新的关联关系是否已存在
        CounselorClass duplicate = counselorClassMapper.selectByCounselorAndClass(
                counselorClassDTO.getCounselorId().intValue(), counselorClassDTO.getClassId().intValue());
        if (duplicate != null) {
            throw new RuntimeException("该辅导员已关联此班级");
        }

        BeanUtils.copyProperties(counselorClassDTO, existingCounselorClass, "id", "createTime");
        existingCounselorClass.setUpdateTime(LocalDateTime.now());
        
        counselorClassMapper.update(existingCounselorClass);
        return existingCounselorClass;
    }

    @Override
    public boolean deleteCounselorClass(Long id) {
        CounselorClass counselorClass = counselorClassMapper.selectById(id.intValue());
        if (counselorClass == null) {
            return false;
        }
        
        return counselorClassMapper.deleteById(id.intValue()) > 0;
    }

    @Override
    public int deleteCounselorClasses(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        List<Integer> intIds = new ArrayList<>();
        for (Long id : ids) {
            intIds.add(id.intValue());
        }
        return counselorClassMapper.deleteByIds(intIds);
    }

    @Override
    public int deleteCounselorClassesByCounselorId(Long counselorId) {
        return counselorClassMapper.deleteByCounselorId(counselorId.intValue());
    }

    @Override
    public int deleteCounselorClassesByClassId(Long classId) {
        return counselorClassMapper.deleteByClassId(classId.intValue());
    }

    @Override
    public boolean deleteCounselorClassByCounselorAndClass(Long counselorId, Long classId) {
        CounselorClass counselorClass = counselorClassMapper.selectByCounselorAndClass(counselorId.intValue(), classId.intValue());
        if (counselorClass == null) {
            return false;
        }
        
        return counselorClassMapper.deleteById(counselorClass.getId()) > 0;
    }

    @Override
    public boolean setPrimaryCounselor(Long counselorId, Long classId) {
        CounselorClass counselorClass = counselorClassMapper.selectByCounselorAndClass(counselorId.intValue(), classId.intValue());
        if (counselorClass == null) {
            return false;
        }
        
        // 先取消该班级的其他主要负责辅导员
        counselorClassMapper.clearPrimaryCounselor(classId.intValue());
        
        // 设置新的主要负责辅导员
        return counselorClassMapper.updatePrimaryCounselor(classId.intValue(), counselorId.intValue()) > 0;
    }



    @Override
    public int getClassCountByCounselorId(Long counselorId) {
        List<CounselorClass> counselorClasses = counselorClassMapper.selectByCounselorId(counselorId.intValue());
        return counselorClasses.size();
    }

    @Override
    public int getCounselorCountByClassId(Long classId) {
        List<CounselorClass> counselorClasses = counselorClassMapper.selectByClassId(classId.intValue());
        return counselorClasses.size();
    }
}